package com.greedy.service;

import com.alibaba.fastjson.JSON;
import com.greedy.bean.pojo.SeckillVoucher;
import com.greedy.bean.pojo.Voucher;
import com.greedy.utils.RedisIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.n3r.eql.Eql;
import org.n3r.eql.EqlTran;
import org.n3r.eql.util.Closes;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.greedy.constants.CommentConstants.SECKILL_STOCK_KEY;

/**
 * @Author: Yanxy
 * @Date: Created in:2022-12-26
 * Description: 商铺优惠券信息
 */
@Slf4j
@Service
public class VoucherService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedisIdWorker redisIdWorker;

    /**
     * 查询店铺的优惠券列表
     * @param shopId 店铺id
     * @return 优惠券列表
     */
    public List<Voucher> queryVoucherOfShop(Long shopId) {
        return new Eql().select("getVoucherByShopId").params(shopId).returnType(Voucher.class).execute();
    }

    /**
     * 新增普通券
     * @param voucher 优惠券信息
     * @return 优惠券id
     */
    public Long save(Voucher voucher) {
        return null;
    }

    /**
     * 新增秒杀券
     * @param voucher 优惠券信息，包含秒杀信息
     * @return 优惠券id
     */
    public Long addSeckillVoucher(Voucher voucher) {
        // 生成秒杀券ID
        long id = redisIdWorker.nextId("seckillVoucherId");
        voucher.setId(id);
        Eql eql = new Eql();
        EqlTran eqlTran = eql.newTran();
        try {
            eqlTran.start();
            // 保存优惠券信息
            eql.insert("insertVoucher").params(voucher).execute();
            // 保存秒杀券信息-MySQL
            SeckillVoucher seckillVoucher = new SeckillVoucher();
            seckillVoucher.setVoucherId(id);
            seckillVoucher.setStock(voucher.getStock());
            eql.insert("insertSeckillVoucher").params(seckillVoucher).execute();
            eqlTran.commit();
            log.info("大白点评-保存秒杀券信息成功-秒杀券信息为：{}", JSON.toJSONString(voucher));
            // 保存秒杀券信息-Redis
            stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + id, String.valueOf(voucher.getStock()));
        } catch (Exception e) {
            eqlTran.rollback();
            log.error("大白点评-保存秒杀券信息失败", e);
        } finally {
            Closes.closeQuietly(eqlTran);
        }
        return id;
    }


}
